// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Util from '../Util';
import { DECODER_TYPE_MAP } from '../config/commonConfig';

class Decode {
    constructor() {
        this.decoderType = DECODER_TYPE_MAP.H264;
        this.moduleInit = false;
        this.util = new Util();
    }

    loadWASM(event) {
        let that = this;
        let libPath = event.data.libPath;
        const decoderType = event.data.decoderType.toUpperCase();
        this.decoderType = DECODER_TYPE_MAP[decoderType];
        self.Module = {
            locateFile: function (wasm) {
                return libPath + wasm;
            }
        }

        self.importScripts(libPath + 'libffmpeg_264_265.js');
        self.Module.onRuntimeInitialized = function() {
            that.openDecode();
        }
    }

    push(data) {
        if (this.moduleInit) {
            this.decodeData(data);
        }
    }

    openDecode() {
        let videoCallback = Module.addFunction(function (addr_y, addr_u, addr_v, stride_y, stride_u, stride_v, width, height, pts) {
            let size = width * height + (width / 2)  * (height / 2) + (width / 2)  * (height / 2);
            let data = new Uint8Array(size);
            let pos = 0;
            for(let i=0; i< height; i++) {
                let src = addr_y + i * stride_y;
                let tmp = HEAPU8.subarray(src, src + width);
                tmp = new Uint8Array(tmp);
                data.set(tmp, pos);
                pos += tmp.length;
            }
            for(let i=0; i< height / 2; i++) {
                let src = addr_u + i * stride_u;
                let tmp = HEAPU8.subarray(src, src + width / 2);
                tmp = new Uint8Array(tmp);
                data.set(tmp, pos);
                pos += tmp.length;
            }
            for(let i=0; i< height / 2; i++) {
                let src = addr_v + i * stride_v;
                let tmp = HEAPU8.subarray(src, src + width / 2);
                tmp = new Uint8Array(tmp);
                data.set(tmp, pos);
                pos += tmp.length;
            }
            let obj = {
                data: data,
                width,
                height
            }

            self.postMessage({
                type: 'decoded',
                data: obj
            });
        });
        let ret = Module._openDecoder(this.decoderType, videoCallback, 1);
        if (ret === 0) {
            this.moduleInit = true;
            console.log('openDecode success');

            // 告诉主线程，解码器准备好了
            self.postMessage({
                type: 'decoderReady',
                data: null
            });
            
        }else {
            console.log('openDecode error');
        }
    }

    decodeData(pes) {
        let fileSize = pes.length;
        let cacheBuffer = Module._malloc(fileSize);
        Module.HEAPU8.set(pes, cacheBuffer);
        Module._decodeData(cacheBuffer, fileSize);
        Module._free(cacheBuffer);
    }

    closeDecode() {
        Module._closeDecoder();
    }
}
export default Decode;